package hygprs

import (
	"hy_808/tcpx"
	"time"
)

/*
用来表示收到的包，可以通过这个包直接发送响应
*/
type Receive struct {
	*tcpx.Conn
	Packet
	UniqueID     int64     // 接收时分配的ID
	ReceivedTime time.Time // 接收时间
	Debug        []string  // debug信息
	ForwardList  []string  // 跳转记录表，上方入栈，先进先出
}

func MakeReceive(c *tcpx.Conn, r tcpx.Package) Receive {
	return Receive{
		UniqueID:     r.UniqueID,
		ReceivedTime: r.ReceivedTime,
		Debug:        r.Debug,
		Packet:       MakePacket(r.Data),
		Conn:         c,
	}
}

func MakeForwardReceive(c *tcpx.Conn, r Receive, e *InternalForward) Receive {
	r2 := MakeReceive(c, tcpx.Package{
		UniqueID:     r.UniqueID,
		ReceivedTime: r.ReceivedTime,
		Data:         e.GetContent(),
		Debug:        r.Debug,
	})
	r2.ForwardList = e.GetList()
	return r2
}

func (p *Receive) Reply(data []byte) {
	if len(p.ForwardList) > 0 {
		data = (*InternalForward).MakeReply(nil, data, p.ForwardList)
	}
	p.Send(tcpx.Package{
		UniqueID:     p.UniqueID,
		ReceivedTime: p.ReceivedTime,
		Data:         data,
	})
}

func PackPackage(header byte, t byte, sn uint16, content []byte) []byte {
	l := len(content) + 12
	b := make([]byte, 0, l)
	b = append(b, header)
	b = append(b, FromUint16(uint16(l))...)
	b = append(b, 2)
	b = append(b, FromUint16(sn)...)
	b = append(b, t)
	b = append(b, content...)
	b = append(b, FromUint32(CheckSum(b))...)
	return append(b, header+1)
}
